/*
 * @Author: wangwenshuai 644586996@qq.com
 * @Date: 2023-03-20 11:09:14
 * @LastEditors: wangwenshuai 644586996@qq.com
 * @LastEditTime: 2023-03-28 15:16:26
 * @FilePath: \carbon_jee\src\utils\WebsocketMixin.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import store from '@/store/'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import Vue from 'vue'
import bus from "@/bus";
export const WebsocketMixin = {
    data() {
        return {
            lockReconnect: false,
            wsConnectErrorTime: 1,

        }
    },
    mounted() {
        this.initWebSocket();
    },
    destroyed() {
        this.websocketOnclose()
    },
    methods: {
        // 初始化
        initWebSocket() {
            let token = Vue.ls.get(ACCESS_TOKEN);
            var userId = store.getters.userInfo.id;
            // console.log(window._CONFIG['domianURL'].replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + userId)
            // var url = window._CONFIG['domianURL'].replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + userId;
            var url = `ws://www.opendbar.cn/zero-carbon-api/websocket/${userId}`;
            console.log(token, userId)
            // 
            this.websock = new WebSocket(url, [token]);
            this.websock.onopen = this.websocketOnopen;
            this.websock.onerror = this.websocketOnerror;
            this.websock.onmessage = this.websocketOnMessage;
            this.websock.onclose = this.websocketOnclose;
        },
        //打开连接
        websocketOnopen() {
            console.log("WebSocket连接成功");
        },
        // 连接错误
        websocketOnerror() {
            console.log('websocket连接发生错误' + this.wsConnectErrorTime)
            this.wsConnectErrorTime++
            if (this.wsConnectErrorTime > 5) {

                console.log("WebSocket连接错误超过5次，就不再重新连了！");
                this.lockReconnect = true
                return;
            }
            this.reconnect()
        },
        websocketOnMessage(e) {
            console.log( e.data);
            var data = eval("(" + e.data + ")");
            console.log(data)
            if (data.messageType == "system") {
                // this.noticeData.push(data);
                bus.$emit('message', data)
            }
        },
        // 在连接
        reconnect() {
            if (this.lockReconnect) return
            setTimeout(() => {
                // console.log('尝试重新连接')
                this.initWebSocket()
                this.lockReconnect = false
            }, 10000)
        },
        // 注销
        websocketOnclose() {
            this.reconnect();
            // console.log(123)
        }
    }

}
